package com.now.printer.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.msd.ocr.idcard.LibraryInitOCR;
import com.now.printer.R;
import com.now.printer.base.BaseActivity2;
import com.now.printer.idcardcamera.camera.CameraActivity;
import com.now.printer.utils.CameraUtils;
import com.xuexiang.xutil.tip.ToastUtils;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;
import com.yuyh.library.imgsel.config.ISListConfig;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.DensityUtil;
import org.xutils.common.util.LogUtil;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 识别身份证开源 demo （驾驶证一样）
 * 实际上识别身份证和驾驶证的API是一样的
 */
public class ScanIdCardActivity extends BaseActivity2 implements Camera.PreviewCallback, SurfaceHolder.Callback, View.OnClickListener {
    private SurfaceView mSurfaceView;
    private SurfaceHolder surfaceHolder;
    private Camera mCamera;
    private ImageView view2;
    private ImageView btnPicPhoto, iv_idcard_front, iv_idcard_back;
    private TextView btnNext;
    private static final int REQUEST_LIST_CODE = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_scan;
    }

    @Override
    public void doBusiness(Context mContext) {

        mSurfaceView = findViewById(R.id.mSurfaceView);
        view2 = findViewById(R.id.view2);
        view2.setImageResource(R.mipmap.camera_idcard_front);
        iv_idcard_front = findViewById(R.id.iv_idcard_front);
        iv_idcard_back = findViewById(R.id.iv_idcard_back);
        LogUtil.i("dp宽： " + DensityUtil.px2dip(240));
        LogUtil.i("dp高： " + DensityUtil.px2dip(151));
        btnNext = findViewById(R.id.btn_next);
        btnNext.setOnClickListener(this);

        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });

        btnPicPhoto = findViewById(R.id.tv_picture_img);
        btnPicPhoto.setOnClickListener(this);

        initPermission();

    }

    private void initHasPermission(){
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//禁止息屏
        this.surfaceHolder = mSurfaceView.getHolder();
        this.surfaceHolder.addCallback(this);
        LibraryInitOCR.initOCR(this);
        LibraryInitOCR.initDecode(this, ocrHandler, true);//第三个参数是是否保存图片
        CameraUtils.init(this);
    }

    private void initPermission() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
//                            toast("获取录音和日历权限成功");
                        } else {
//                            toast("获取部分权限成功，但部分权限未正常授予");
                        }
                        initHasPermission();
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
//                            toast("被永久拒绝授权，请手动授予录音和日历权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(ScanIdCardActivity.this, permissions);
                        } else {
//                            toast("获取录音和日历权限失败");
                        }
                        initHasPermission();

                    }
                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_picture_img:
                // 跳转到图片选择器
                ISNav.getInstance().toListActivity(this, config, REQUEST_LIST_CODE);
                break;
            case R.id.btn_next:
                if (TextUtils.isEmpty(currentFront)) {
                    ToastUtils.toast("请识别正面");
                    return;
                }
                if (TextUtils.isEmpty(currentBack)) {
                    ToastUtils.toast("请识别反面");
                    return;
                }
                Intent intent = new Intent(this, FilePreviewAndPrintActivity.class);
                intent.putExtra(CameraActivity.INTENT_KEY_ID_CARD_FRONT_BACK, frontAndBackImagePath);
                startActivity(intent);

                break;

        }
    }

    /**
     * 初始化handler
     * /*身份证相关
     *                             type:正面
     *                             sex:性别
     *                             folk:民族
     *                             birt:日期
     *                             num:号码
     *                             addr:住址
     *                             issue:签发机关
     *                             valid:有效期限
     *                             imgPath:整体照片
     *                             headPath:头像路径
     *
     *                             驾驶证相关
     *                             nation：国家
     *                             startTime：初始领证
     *                             drivingType：准驾车型
     *                             registerDate：有效期限
     */
    Handler ocrHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //解码成功
                case LibraryInitOCR.DECODE_SUCCESS: {
                    Intent intent = (Intent) msg.obj;
                    String result = intent.getStringExtra("OCRResult");
                    JSONObject jsonRes = null;
                    try {
                        jsonRes = new JSONObject(result);

                        String idcard = jsonRes.optString("num");
                        String realname = jsonRes.optString("name");
                        Intent i = new Intent();
                        String ocrResult = "姓名：" + realname + "\n"
                                + "身份证号:" + idcard + "\n";
                        i.putExtra("OCRResult", ocrResult);
//                            setResult(RESULT_OK, i);
//                            finish();
                        startPreviewAndPrintActivity(jsonRes);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                //解码失败
                case LibraryInitOCR.DECODE_FAIL: {
                    break;
                }
            }
        }
    };
    private String currentFront = "";
    private String currentBack = "";

    private String[] frontAndBackImagePath = new String[2];

    private void startPreviewAndPrintActivity(JSONObject jsonRes) {
        LogUtil.i("识别的数据是：" + jsonRes);
        if (jsonRes != null) {
            String type = jsonRes.optString("type");
            String imgPath = jsonRes.optString("imgPath");
            if (TextUtils.equals(type, "1")) {
                currentFront = type;
                Glide.with(this).load(imgPath).into(iv_idcard_front);
                frontAndBackImagePath[0] = imgPath;
                ToastUtils.toast("识别到正面");
                view2.setImageResource(R.mipmap.camera_idcard_back);
            } else {
                currentBack = type;
                Glide.with(this).load(imgPath).into(iv_idcard_back);
                frontAndBackImagePath[1] = imgPath;
                ToastUtils.toast("识别到反面");

            }
        }
    }

    /**
     * 初始化相机
     */
    void initCamera() {
        try {
            mCamera.setPreviewCallback(this);
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setPreviewFormat(ImageFormat.NV21);
            //根据设置的宽高 和手机支持的分辨率对比计算出合适的宽高算法
            Camera.Size optionSize = CameraUtils.findBestPreviewResolution(mCamera);
            // parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//部分手机无效
            parameters.setPreviewSize(optionSize.width, optionSize.height);
            //设置照片尺寸
            parameters.setPictureSize(optionSize.width, optionSize.height);
            mCamera.setParameters(parameters);
            //开启预览
            mCamera.startPreview();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放相机
     */
    void closeCamera() {
        try {
            if (autoFocusTimer != null) {
                autoFocusTimer.cancel();
            }
            if (mCamera != null) {
                mCamera.stopPreview();
                //mCamera.release();//加上要挂啊
                mCamera = null;
            }
            LibraryInitOCR.closeDecode();
        } catch (Exception e) {
        }
    }

    @Override
    public void finish() {
        super.finish();
        closeCamera();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mCamera = Camera.open(0);//0:后置 1：前置
            initCamera();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        try {
            mCamera.setPreviewDisplay(holder);
            initAutoFocusTimer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        closeCamera();
    }

    private byte[] data;

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        this.data = data;
    }

    Timer autoFocusTimer;

    void initAutoFocusTimer() {
        if (autoFocusTimer == null) {
            autoFocusTimer = new Timer();
            autoFocusTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mCamera != null) {
                        mCamera.autoFocus(new Camera.AutoFocusCallback() {
                            @Override
                            public void onAutoFocus(boolean success, Camera camera) {
                                if (data != null) {
                                    Camera.Size size = mCamera.getParameters().getPreviewSize();
                                    Rect rect = new Rect();
                                    rect.top = view2.getTop();
                                    rect.right = view2.getRight();
                                    rect.left = view2.getLeft();
                                    rect.bottom = view2.getBottom();
                                    LibraryInitOCR.decode(rect, size.width, size.height, data);
                                    if (mCamera != null) {
                                        mCamera.cancelAutoFocus();
                                    }
                                }
                            }
                        });

                    }
                }
            }, 0, 3000);
        }
    }

    // 自由配置选项
    ISListConfig config = new ISListConfig.Builder()
            // 是否多选, 默认true
            .multiSelect(true)
            // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
            .rememberSelected(false)
            // “确定”按钮背景色
            .btnBgColor(Color.GRAY)
            // “确定”按钮文字颜色
            .btnTextColor(Color.BLUE)
            // 使用沉浸式状态栏
            .statusBarColor(Color.parseColor("#3F51B5"))
            // 返回图标ResId
            .backResId(R.mipmap.fanhuibai)
            // 标题
            .title("图片")
            // 标题文字颜色
            .titleColor(Color.WHITE)
            // TitleBar背景色
            .titleBgColor(Color.parseColor("#3F51B5"))
            // 裁剪大小。needCrop为true的时候配置
            .cropSize(1, 1, 200, 200)
            .needCrop(true)
            // 第一个是否显示相机，默认true
            .needCamera(false)
            // 最大选择图片数量，默认9
            .maxNum(2)
            .build();


    private int remeberCount = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        remeberCount++;
        LogUtil.i("记录本次选择 ：" + remeberCount);
        // 图片选择结果回调
        if (requestCode == REQUEST_LIST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra("result");
            LogUtil.i("图片路径是 : " + pathList);

            for (int i = 0; i < pathList.size(); i++) {
                frontAndBackImagePath[i] = pathList.get(i);

            }
            Intent intent = new Intent(this, FilePreviewAndPrintActivity.class);
            intent.putExtra(CameraActivity.INTENT_KEY_ID_CARD_FRONT_BACK, frontAndBackImagePath);
            startActivity(intent);

//            if (remeberCount == 1) {
//                ///storage/emulated/0/Android/data/com.now.printer/cache/1623893740623.jpg
//                frontAndBackImagePath[0] = pathList.get(0);
//                // 跳转到图片选择器
//                ISNav.getInstance().toListActivity(this, config, REQUEST_LIST_CODE);
//            } else if (remeberCount == 2) {
//                frontAndBackImagePath[1] = pathList.get(0);
//            }

        }
    }

}
